<template>
  <div class="policy-advanced-container">
    <!-- 增强的头部区域 -->
    <header class="advanced-header">
      <div class="header-container">
        <div class="emergency-header">
          <div class="black-block"></div>
          <div class="red-title">
            <el-icon><document /></el-icon>
            政策信息
          </div>
        </div>
      </div>

      <!-- 复合搜索筛选区 -->
      <div class="advanced-filter">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-input
              v-model="searchQuery"
              placeholder="输入政策标题、内容或关键词"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon class="search-icon"><Search /></el-icon>
              </template>
              <template #append>
                <el-button type="danger" @click="handleSearch">
                  搜索<el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="danger" @click="showFilter = !showFilter">
              高级筛选<el-icon><Filter /></el-icon>
            </el-button>
          </el-col>
        </el-row>

        <!-- 高级筛选面板 -->
        <transition name="el-zoom-in-top">
          <div v-show="showFilter" class="filter-panel">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-select
                  v-model="selectedTags"
                  multiple
                  collapse-tags
                  placeholder="选择标签"
                >
                  <el-option
                    v-for="tag in allTags"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select
                  v-model="selectedDepartment"
                  clearable
                  placeholder="选择发布部门"
                >
                  <el-option
                    v-for="dept in allDepartments"
                    :key="dept"
                    :label="dept"
                    :value="dept"
                  />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-col>
              <el-col :span="6">
                <el-select
                  v-model="sortField"
                  placeholder="排序方式"
                >
                  <el-option
                    v-for="item in sortOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
            </el-row>
          </div>
        </transition>
      </div>
    </header>

    <!-- 政策列表主体 -->
    <main class="policy-main-content">
      <div class="statistics-bar">
        <el-space :size="30">
          <span>共 {{ total }} 条政策</span>
          <el-divider direction="vertical" />
          <span>当前显示：{{ paginatedPolicies.length }} 条</span>
          <el-tag type="danger" effect="dark">
            最新政策日期：{{ latestDate }}
          </el-tag>
        </el-space>
      </div>

      <div class="scrollable-content">
        <!-- 骨架屏加载效果 -->
        <template v-if="loading">
          <div
            v-for="i in pageSize"
            :key="i"
            class="skeleton-item"
          >
            <el-skeleton :animated="true">
              <template #template>
                <div class="skeleton-content">
                  <el-skeleton-item variant="h3" style="width: 40%" />
                  <el-skeleton-item variant="text" style="width: 60%" />
                  <el-skeleton-item variant="text" style="width: 30%" />
                </div>
              </template>
            </el-skeleton>
          </div>
        </template>

        <!-- 实际政策列表 -->
        <template v-else>
          <transition-group name="list">
            <article
              v-for="policy in paginatedPolicies"
              :key="policy.id"
              class="policy-article-card"
              :class="{ 'starred': policy.starred }"
            >
              <div class="card-body" @click="showPolicyDetail(policy)">
                <div class="policy-meta">
                  <el-tag
                    v-for="tag in policy.tags"
                    :key="tag"
                    :type="tagTypeMap[tag]"
                    effect="light"
                    class="tag-item"
                  >
                    {{ tag }}
                  </el-tag>
                  <time class="publish-date">{{ formatDate(policy.publishDate) }}</time>
                </div>
                <h2 class="policy-title">
                  {{ policy.title }}
                  <el-icon
                    v-if="isNewPolicy(policy)"
                    class="new-badge"
                    color="#F56C6C"
                  >
                    <ArrowUpBold />
                  </el-icon>
                </h2>
                <div class="policy-summary">
                  {{ truncateContent(policy.content, 120) }}
                </div>
                <div class="policy-footer">
                  <div class="department-info">
                    <el-icon><OfficeBuilding /></el-icon>
                    {{ policy.department }}
                  </div>
                  <div class="interaction-buttons">
                    <el-button
                      type="primary"
                      size="small"
                      link
                      @click.stop="toggleStar(policy)"
                    >
                      <el-icon class="mr-1">
                        <StarFilled v-if="policy.starred" />
                        <Star v-else />
                      </el-icon>
                      {{ policy.starred ? '已收藏' : '收藏' }}
                    </el-button>
                    <el-divider direction="vertical" />
                    <el-button
                      type="primary"
                      size="small"
                      link
                      @click.stop="showPolicyDetail(policy)"
                    >
                      查看详情
                    </el-button>
                  </div>
                </div>
              </div>
              <div class="card-divider"></div>
            </article>
          </transition-group>

          <!-- 空状态 -->
          <el-empty
            v-if="!paginatedPolicies.length && !loading"
            description="未找到相关政策"
            class="empty-state"
          >
            <template #image>
              <el-icon class="empty-icon"><DocumentDelete /></el-icon>
            </template>
            <el-button type="primary" @click="resetFilters">重置筛选条件</el-button>
          </el-empty>
        </template>
      </div>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredPolicies.length"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </main>

    <!-- 政策侧边抽屉 -->
    <el-drawer
      v-model="detailVisible"
      direction="rtl"
      size="60%"
      class="policy-drawer"
    >
      <div v-if="currentPolicy" class="drawer-content">
        <div class="drawer-header">
          <h2 class="drawer-title">{{ currentPolicy.title }}</h2>
          <div class="meta-info">
            <el-tag
              v-for="tag in currentPolicy.tags"
              :key="tag"
              :type="tagTypeMap[tag]"
              class="tag-margin"
            >
              {{ tag }}
            </el-tag>
            <div class="date-info">
              <span>发布日期：{{ formatDate(currentPolicy.publishDate) }}</span>
              <el-divider direction="vertical" />
              <span>生效日期：{{ formatDate(currentPolicy.effectiveDate) }}</span>
            </div>
          </div>
        </div>

        <el-scrollbar class="drawer-scrollbar">
          <div class="detail-section">
            <h3><el-icon><Document /></el-icon> 政策内容</h3>
            <pre class="policy-content">{{ currentPolicy.content }}</pre>
          </div>

          <div class="detail-section">
            <h3><el-icon><InfoFilled /></el-icon> 发布信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <label>发布部门：</label>
                <el-tag type="warning">{{ currentPolicy.department }}</el-tag>
              </div>
              <div class="info-item">
                <label>联系方式：</label>
                <span class="copyable" @click="copyContact(currentPolicy.contact)">
                  {{ currentPolicy.contact }}
                  <el-icon class="copy-icon"><DocumentCopy /></el-icon>
                </span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h3><el-icon><Paperclip /></el-icon> 附件下载</h3>
            <div class="file-list">
              <div
                v-for="file in currentPolicy.attachments"
                :key="file.name"
                class="file-item"
              >
                <el-icon class="file-icon"><Document /></el-icon>
                <div class="file-info">
                  <span class="file-name">{{ file.name }}</span>
                  <span class="file-size">{{ file.size }}</span>
                </div>
                <el-button
                  type="danger"
                  size="small"
                  @click="downloadFile(file)"
                >
                  下载
                </el-button>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h3><el-icon><Connection /></el-icon> 相关法律</h3>
            <div class="related-laws">
              <el-tag
                v-for="law in currentPolicy.relatedLaws"
                :key="law"
                class="law-tag"
                type="danger"
                @click="searchLaw(law)"
              >
                {{ law }}
              </el-tag>
            </div>
          </div>
        </el-scrollbar>

        <div class="drawer-footer">
          <el-button
            type="danger"
            @click="openLink(currentPolicy.link)"
          >
            查看官方原文
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  Document,
  Search,
  Star,
  StarFilled,
  Filter,
  OfficeBuilding,
  ArrowUpBold,
  InfoFilled,
  Paperclip,
  Connection,
  DocumentCopy,
  DocumentDelete
} from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'
import type { TagProps } from 'element-plus'

interface Policy {
  id: number
  title: string
  content: string
  publishDate: string
  effectiveDate: string
  department: string
  tags: string[]
  starred: boolean
  attachments: {
    name: string
    size: string
    url: string
  }[]
  relatedLaws: string[]
  link: string
  contact: string
}

// 响应式数据
const searchQuery = ref('')
const loading = ref(false)
const detailVisible = ref(false)
const currentPolicy = ref<Policy>()
const policies = ref<Policy[]>([])
const currentPage = ref(1)
const pageSize = ref(10)

// 筛选相关
const showFilter = ref(false)
const selectedTags = ref<string[]>([])
const selectedDepartment = ref('')
const dateRange = ref<string[]>([])
const sortField = ref('publishDate')
const sortOptions = ref([
  { label: '发布日期', value: 'publishDate' },
  { label: '生效日期', value: 'effectiveDate' },
  { label: '政策标题', value: 'title' }
])

// 类型映射
const tagTypeMap: Record<string, TagProps['type']> = {
  '紧急': 'danger',
  '民生': 'success',
  '法律': 'warning',
  '财政': 'info',
  '教育': 'info',
  '医疗': 'info'
}

// 计算属性
const filteredPolicies = computed(() => {
  let result = policies.value.filter(policy => {
    const matchesSearch = policy.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      policy.content.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      policy.tags.some(tag => tag.toLowerCase().includes(searchQuery.value.toLowerCase()))

    const matchesTags = selectedTags.value.length === 0 ||
      selectedTags.value.every(tag => policy.tags.includes(tag))

    const matchesDepartment = !selectedDepartment.value ||
      policy.department === selectedDepartment.value

    const matchesDate = dateRange.value.length === 0 || (
      new Date(policy.publishDate) >= new Date(dateRange.value[0]) &&
      new Date(policy.publishDate) <= new Date(dateRange.value[1])
    )

    return matchesSearch && matchesTags && matchesDepartment && matchesDate
  })

  // 排序逻辑
  if (sortField.value) {
    result = result.sort((a, b) => {
      if (sortField.value === 'publishDate' || sortField.value === 'effectiveDate') {
        return new Date(b[sortField.value]).getTime() - new Date(a[sortField.value]).getTime()
      }
      return a.title.localeCompare(b.title)
    })
  }

  return result
})

const paginatedPolicies = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredPolicies.value.slice(start, end)
})

const total = computed(() => filteredPolicies.value.length)

const allTags = computed(() => {
  const tags = policies.value.flatMap(p => p.tags)
  return [...new Set(tags)]
})

const allDepartments = computed(() => {
  const depts = policies.value.map(p => p.department)
  return [...new Set(depts)]
})

const latestDate = computed(() => {
  if (policies.value.length === 0) return '--'
  const dates = policies.value.map(p => new Date(p.publishDate).getTime())
  const latest = new Date(Math.max(...dates))
  return latest.toLocaleDateString()
})

// 方法
const fetchPolicies = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    policies.value = [
    {
        id: 1,
        title: '失踪人口救助法',
        content: `第一章 总则\n第一条 为了保护失踪人口及其家属的合法权益，制定本法...`,
        publishDate: '2023-01-15',
        effectiveDate: '2023-03-01',
        department: '民政部',
        tags: ['法律', '社会'],
        starred: false,
        attachments: [
          {
            name: '失踪人口救助法全文.pdf',
            size: '1.2MB',
            url: '/laws/missing-persons-assistance.pdf'
          }
        ],
        relatedLaws: ['刑法第234条', '民法典第104条'],
        link: 'http://law.gov/missing-persons-assistance',
        contact: '失踪人口热线：12345'
      },
      {
        id: 2,
        title: '失踪人口信息登记管理办法',
        content: '明确失踪人口信息的登记、管理和发布机制...',
        publishDate: '2023-04-20',
        effectiveDate: '2023-06-01',
        department: '公安部',
        tags: ['法律', '社会'],
        starred: true,
        attachments: [
          {
            name: '失踪人口信息登记管理办法.docx',
            size: '1.5MB',
            url: '/laws/missing-persons-registration.docx'
          }
        ],
        relatedLaws: ['治安管理处罚法', '反家庭暴力法'],
        link: 'http://police.gov/missing-persons-registration',
        contact: '举报电话：110'
      },
      {
        id: 3,
        title: '失踪儿童保护法',
        content: '针对失踪儿童的保护措施和救助机制...',
        publishDate: '2023-07-01',
        effectiveDate: '2023-09-01',
        department: '儿童保护委员会',
        tags: ['法律', '儿童'],
        starred: false,
        attachments: [
          {
            name: '失踪儿童保护法.pdf',
            size: '1.0MB',
            url: '/laws/missing-children-protection.pdf'
          }
        ],
        relatedLaws: ['未成年人保护法', '刑法第237条'],
        link: 'http://children.gov/missing-children-protection',
        contact: '儿童保护热线：12348'
      },
      {
        id: 4,
        title: '失踪人口救助基金管理办法',
        content: '为失踪人口及其家属提供经济支持的管理办法...',
        publishDate: '2023-08-15',
        effectiveDate: '2023-10-01',
        department: '民政部',
        tags: ['法律', '社会'],
        starred: false,
        attachments: [
          {
            name: '失踪人口救助基金管理办法.pdf',
            size: '1.3MB',
            url: '/laws/missing-persons-fund-management.pdf'
          }
        ],
        relatedLaws: ['社会救助法', '民法典'],
        link: 'http://law.gov/missing-persons-fund-management',
        contact: '热线电话：12345'
      },
      {
        id: 5,
        title: '失踪人口案件侦查程序',
        content: '规范失踪人口案件的侦查程序和责任...',
        publishDate: '2023-09-10',
        effectiveDate: '2023-11-01',
        department: '公安部',
        tags: ['法律', '侦查'],
        starred: true,
        attachments: [
          {
            name: '失踪人口案件侦查程序.docx',
            size: '1.4MB',
            url: '/laws/missing-persons-investigation-procedure.docx'
          }
        ],
        relatedLaws: ['刑事诉讼法', '治安管理处罚法'],
        link: 'http://police.gov/missing-persons-investigation-procedure',
        contact: '举报电话：110'
      }
      // 更多模拟数据...
    ]
  } catch (error) {
    ElNotification.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

const toggleStar = (policy: Policy) => {
  policy.starred = !policy.starred
  ElMessage.success(policy.starred ? '已加入收藏' : '已取消收藏')
}

const showPolicyDetail = (policy: Policy) => {
  currentPolicy.value = policy
  detailVisible.value = true
}

const truncateContent = (text: string, length: number) => {
  return text.length > length ? text.slice(0, length) + '...' : text
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

const isNewPolicy = (policy: Policy) => {
  const publishDate = new Date(policy.publishDate)
  const now = new Date()
  const diffTime = now.getTime() - publishDate.getTime()
  return diffTime < 30 * 24 * 60 * 60 * 1000 // 30天内为新政策
}

const resetFilters = () => {
  searchQuery.value = ''
  selectedTags.value = []
  selectedDepartment.value = ''
  dateRange.value = []
  sortField.value = 'publishDate'
  currentPage.value = 1
}

const handleSearch = () => {
  currentPage.value = 1
}

const handlePageChange = (page: number) => {
  currentPage.value = page
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const downloadFile = (file: Policy['attachments'][number]) => {
  window.open(file.url, '_blank')
  ElMessage.success('开始下载文件')
}

const copyContact = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制联系方式')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

const searchLaw = (law: string) => {
  searchQuery.value = law
  detailVisible.value = false
}

const openLink = (url: string) => {
  window.open(url, '_blank')
}

// 生命周期
onMounted(() => {
  fetchPolicies()
})
</script>

<style scoped lang="scss">
.policy-advanced-container {
  width: 100%;
  margin: 0 auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 5px 15px 5px;

  .advanced-header {
    margin-bottom: 10px;

    .header-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      gap: 20px;
    }
    .emergency-header {
      display: flex;
      height: 50px;
      border-radius: 6px;
      flex-shrink: 0;
    }
    .black-block {
      width: 10px;
      background: var(--reverse-background-color);
    }
    .red-title {
      flex: 1;
      background: #f45c5c;
      color: white;
      display: flex;
      align-items: center;
      padding: 0 20px;
      font-size: 22px;
      font-weight: 600;
      gap: 10px;
    }
  }

  .policy-main-content {
    border: 1px solid;
    border-radius: 8px;
    padding: 0;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    flex: 1;
    display: flex;
    flex-direction: column;
    max-height: calc(100vh - 100px);
    overflow: hidden;

    .statistics-bar {
      padding: 16px 32px;
      border-bottom: 1px solid;
      font-size: 14.4px;
      z-index: 1;
    }

    .scrollable-content {
      flex: 1;
      overflow-y: auto;
    }

    .policy-article-card {
      position: relative;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &.starred {
        border-left: 4px solid #f7ba2a;
      }

      .card-body {
        padding: 24px;
        cursor: pointer;

        .policy-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 12px;

          .tag-item {
            font-size: 12px;
            padding: 0 8px;
            height: 24px;
          }

          .publish-date {
            font-size: 12px;
          }
        }

        .policy-title {
          font-size: 16px;
          margin-bottom: 12px;
          display: flex;
          align-items: center;

          .new-badge {
            margin-left: 8px;
            animation: pulse 1.5s infinite;
          }
        }

        .policy-summary {
          line-height: 1.6;
          font-size: 14px;
          margin-bottom: 16px;
        }

        .policy-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 13.6px;

          .department-info {
            display: flex;
            align-items: center;

            .el-icon {
              margin-right: 4px;
              font-size: 16px;
            }
          }

          .interaction-buttons {
            display: flex;
            align-items: center;
            gap: 8px;

            .el-divider {
              margin: 0 8px;
            }
          }
        }
      }

      .card-divider {
        border-bottom: 1px solid;
        margin: 0 24px;
      }

      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 16px rgba(0,0,0,0.1);
      }
    }

    .empty-state {
      padding: 48px 0;
      text-align: center;

      .empty-icon {
        font-size: 64px;
        margin-bottom: 16px;
      }
    }

    .pagination-container {
      margin-top: auto;
      padding: 10px;
      display: flex;
      justify-content: center;
    }
  }

  .policy-drawer {
    .drawer-content {
      padding: 10px;
      height: calc(100vh - 100px);
      display: flex;
      flex-direction: column;
      margin-top: -20px;
      .drawer-header {
        margin-bottom: 24px;

        .drawer-title {
          font-size: 24px;
          margin-bottom: 16px;
        }

        .meta-info {
          .tag-margin {
            margin-right: 8px;
            height: 28px;
          }

          .date-info {
            margin-top: 10px;
            font-size: 14px;
            display: flex;
            align-items: center;

            .el-divider {
              height: 20px;
            }
          }
        }
      }

      .detail-section {
        margin-bottom: 22px;

        h3 {
          font-size: 16px;
          margin-bottom: 5px;
          display: flex;
          align-items: center;

          .el-icon {
            margin-right: 8px;
            font-size: 20px;
          }
        }

        .policy-content {
          white-space: pre-wrap;
          line-height: 1.2;
          padding: 16px;
          border-radius: 4px;
          font-family: 'Microsoft YaHei', sans-serif;
          border: 1px solid;
          height: 20vh;
        }

        .info-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 10px;

          .info-item {
            display: flex;
            align-items: center;
            padding: 8px 0;

            label {
              min-width: 80px;
              font-size: 14px;
            }

            .copyable {
              cursor: pointer;
              display: flex;
              align-items: center;

              &:hover {
                color: #9b2a2a;
                text-decoration: underline;
              }

              .copy-icon {
                margin-left: 4px;
                font-size: 14px;
              }
            }
          }
        }

        .file-list {
          .file-item {
            display: flex;
            align-items: center;
            padding: 12px;
            border-bottom: 1px solid;

            .file-icon {
              font-size: 20px;
              margin-right: 8px;
            }

            .file-info {
              flex: 1;

              .file-name {
                display: block;
                font-size: 15.2px;
              }

              .file-size {
                font-size: 12px;
              }
            }
          }
        }

        .related-laws {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;

          .law-tag {
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            }
          }
        }
      }

      .drawer-scrollbar {
        flex: 1;

        .el-scrollbar__view {
          padding-right: 16px;
        }
      }

      .drawer-footer {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .policy-advanced-container {
    padding: 16px;

    .advanced-header {
      .main-title {
        font-size: 22.4px;
      }
    }

    .policy-main-content {
      padding: 16px;

      .policy-article-card {
        margin-bottom: 8px;

        .card-body {
          padding: 16px;
        }
      }
    }

    .filter-panel {
      padding: 16px;

      .el-col {
        width: 100%;
        margin-bottom: 16px;
      }
    }
  }

  .policy-drawer {
    width: 100% !important;

    .drawer-content {
      padding: 16px;

      .info-grid {
        grid-template-columns: 1fr;
      }
    }
  }
}
</style>
